import {
  api,
  util,
} from "../util";
import {
  router
} from '../router';
import authorize from './authorize.js'
const app = getApp();
app.globalData.flag = false;
const orderPay = {
  /**提交订单成功后获取跳转收银台需要的参数 */
  findPayOrderData(payData, path,callback,isSkip=true) {
    var entity = authorize.getEntity();
    var param = {
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      Token: entity && entity.manager ? entity.manager.Token : '',
      Type: 0,
      DataType: 1,
      Terminal: 5,
      Content: "<Data>" + payData + "</Data>",
      ProprietorId: app.dns.proprietorId
    };
    util.post("payment.cashier.passport", param, function(res) {
      res = res.data;
      if (!res.Success) {
        util.alert(res.Message);
        if (callback&&typeof (callback)=="function"){
          callback();
        }
        return;
      } else {
        var recordToken = res.Content.recordToken;
        if (!isSkip){
          if (callback && typeof (callback) == "function") {
            callback(recordToken);
          }
        }
        else{
          var entity = authorize.getEntity();
          router.navigate({
          path: path,
          params: {
            paytoken: recordToken,
            pagetype: 'order',
            cashier: entity==undefined?'alone':''
          }
        });
        }
      }
    },"3.0",null,false);
  }
}
const cashier = {
  /**获取收银台订单数据 */
  loadCashierOrderData(recordToken, callback) {
    var param = {
      recordToken: recordToken,
      ProprietorId: app.dns.proprietorId,
      proprietor:app.dns.proprietor
    };
    util.post("payment.record.get", param, function(res) {
      res = res.data;
      if (!res.Success) {
        util.tips(res.Message);
        return;
      }
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.Content);
      }
    },"3.0");
  },
  /**获取收银台支付数据 */
  loadCashierPayData(recordToken,status,reData, callback) {
    var entity = authorize.getEntity();
    var param = {
      proprietorId: app.dns.proprietorId,
      token: status && entity && entity.manager ? entity.manager.Token : '',
      recordToken: recordToken,
      proprietor: app.dns.proprietor,
    };
    util.post("payment.pay.applied", param, function(res) {
      res = res.data;
      if (!res.Success) {
        if(res.Message!=''){
          util.tips(res.Message);
        }
        return;
      }
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.Content);
      }
    }, "3.0",null,false);
  },
  /**显示转账汇款的明细 */
  showRemit(appliedId, callback) {
    var param = {
      AppliedId: appliedId,
      ProprietorId: app.dns.proprietorId
    };
    util.post("payment.transfer.applied", param, function(res) {
      res = res.data;
      if (!res.Success) {
        util.tips(res.Message);
        return;
      }
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.Content);
      }
    }, "3.0",null,false);
  },
  /**支付验证手机号 */
  verifyMobile(param,method,callback){
    util.post(method, param, function(res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof(callback) == "function") {
          callback(res.data);
        }
      } else {
        util.alert(res.Message);
      }
    },"3.0");
  },
  getMicroPayData(callback){
    util.get('https://mqq-imgcache.gtimg.cn/wuji/object/623adccbd761c512f88f6c84?appid=msepay&schemaid=scene_side_config&appkey=45ab880b38af407a965481c737a09ddd', callback);
  }
}

const payment = {
  /**主动查询 */
  monitorPay(recordToken, callback) {
    var param = {
      recordToken: recordToken,
      ProprietorId: app.dns.proprietorId
    };
    util.post("payment.monitor.pay", param, function(res) {
      if (res.data.Success && res.data.Content == '1') {
        if (callback != undefined && typeof(callback) == "function") {
          callback(true);
        }
      } else {
        if (callback != undefined && typeof(callback) == "function") {
          callback(false);
        }
      }
    }, "3.0");
  },
  /**获取用户的小程序openid */
  getOpenId(selfVal,callback,failCallback) {
    var entity = authorize.getEntity();
    wx.login({
      success: res => {
        var param = {
          proprietorId:selfVal.validateLogin?app.dns.proprietorId:selfVal.proprietorId,
          fKId: selfVal.validateLogin?app.dns.proprietorId:selfVal.fKId,
          fKFlag:  selfVal.validateLogin?app.dns.proprietor:selfVal.fKFlag,
          fk_way: app.dns.fkWay,
          code: res.code,
          Token: entity && entity.manager ? entity.manager.Token : ''
        };
        util.post("social.minpro.authorize.info", param, function(res) {
          res = res.data;
          if (res.Success) {
            if (callback != undefined && typeof(callback) == "function") {
              callback(res.Content.openid);
            }
          } else {
            util.alert("支付对象验证失败，请稍后重试!"+res.Message);
            if (failCallback != undefined && typeof(failCallback) == "function") {
              failCallback();
            }
          }
        },"3.0");
      }
    });
  },
  /**微信支付 */
  wechatPay(data, selfVal, callback, failCallback) {
    this.getOpenId(selfVal,function(openid) {
      var param = {
        recordToken: data.recordToken,
        paymentId: data.paymentId,
        openid: openid,
        TradeType: 0,
        ProprietorId: app.dns.proprietorId
      };
      util.post("payment.wechat.pay", param, function(res) {
        res=res.data;
        if (res.Success) {
          if (callback != undefined && typeof(callback) == "function") {
            callback(res.Content);
          }
        } else {
          util.alert("支付失败："+res.Message);
          if (failCallback != undefined && typeof(failCallback) == "function") {
            failCallback();
          }
        }
      }, "3.0");
    },function(){
      if (failCallback != undefined && typeof(failCallback) == "function") {
        failCallback();
      }
    });
  },
  wxRequesPay(data, callback, failCallback) {
    // 发起微信支付
    wx.requestPayment({
      'timeStamp': data.timeStamp,
      'nonceStr': data.nonceStr,
      'package': data.package,
      'signType': data.signType == 'RSA' ?'RSA':'MD5',
      'paySign': data.paySign,
      'success': function(rtpy) {
        console.log('pay success', rtpy)
        if (rtpy.errMsg == 'requestPayment:ok') {
          if (callback != undefined && typeof(callback) == "function") {
            callback();
          }
        }
      },
      'fail': function(rtpy) {
        console.log('pay fail', rtpy)
        util.alert("支付失败");
        if (failCallback != undefined && typeof(failCallback) == "function") {
          failCallback();
        }
      }
    });
  },
  /**预存款支付 */
  prestorePay(data, callback) {
    var param = {
      recordToken: data.payToken,
      payPassword: data.payPassword,
      paymentId: data.payId,
      mobileToken: data.mobileToken,
      mobileCode: data.mobileCode,
      proprietorId:app.dns.proprietorId
    };
    util.post("payment.prepay.pay", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data);
      }
    }, "3.0", null, false);
  },
  /**授信支付 */
  creditPay(data, callback) {
    var param = {
      recordToken: data.payToken,
      payPassword: data.payPassword,
      appliedId: data.payId,
      mobileToken: data.mobileToken,
      mobileCode: data.mobileCode,
      proprietorId:app.dns.proprietorId,
      proprietor:app.dns.proprietor
    };
    util.post("payment.credit.pay", param, function (res) {
      if (callback != undefined && typeof (callback) == "function") {
        callback(res.data);
      }
    }, "3.0", null, false);
  },
  /**在线支付 */
  cashierPay(data, callback) {
    var entity = authorize.getEntity();
    var param = {
      recordToken: data.payToken || '',
      payTypeId: data.payTypeId || '',
      PaymentId: data.payId || '',
      Token: entity && entity.manager ? entity.manager.Token : '',
      proprietorId: app.dns.proprietorId,
      proprietor: app.dns.proprietor
    };
    util.post("payment.cashier.pay", param, function (res) {
      if (callback != undefined && typeof (callback) == "function") {
        callback(res.data);
      }
    }, "3.0", null, false);
  },
  /**
   * 获得错误 信息
   */
  get_error_msg: function (res) {
    var code=res.Code;
    if (isNaN(Number(res.Content))){
      return res.Content;
    } else{
      code = res.Content;
    }
    var list = [
      { code: 4, txt: '此支付单金额发生变化！请重新发起支付请求.' },
      { code: 91, txt: '支付参数口令发生错误！请刷新重试.' },
      { code: 100, txt: '支付参数为空！' },
      { code: 101, txt: '此单号已支付，请勿重复发起支付！' },
      { code: 102, txt: '未找到相应的支付信息' },
      { code: 103, txt: '未找到支付配置信息' },
      { code: 104, txt: '支付信息装载异常！' },
      { code: 105, txt: '支付信息加载异常！' },
      { code: 106, txt: '支付参数解析失败！' },
      { code: 107, txt: '暂不支持此支付方式！' },
      { code: 110, txt: '未找到相应的支付请求' },
      { code: 111, txt: '当前支付请求已支付' },
      { code: 112, txt: '未设置初始支付密码' },
      { code: 113, txt: '输入支付密码不正确！' },
      { code: 114, txt: '输入支付密码不正确' },
      { code: 115, txt: '微信扫码发起异常' },
      { code: 120, txt: '未开通预存款功能！' },
      { code: 121, txt: '预存款余额不足' },
      { code: 122, txt: '预存款支付失败' },
      { code: 150, txt: '金额发生变化，支付金额与订单金额不一致！请重新发起支付' },
      { code: 196, txt: '收款失败！核销订单编号信息错误.' },
      { code: 197, txt: '订单核销失败！请稍后重试' },
      { code: 198, txt: '线下收款失败' },
      { code: 199, txt: '保证缴纳支付失败' },
      { code: 200, txt: '订单支付支付失败' },
      { code: 201, txt: '账户充值支付失败' },
      { code: 202, txt: '积分购买支付失败' },
      { code: 203, txt: '短信购买支付失败' },
      { code: 204, txt: '授信还款支付失败' },

      { code: 400, txt: '授信支付成功' },
      { code: 401, txt: '授信未开通' },
      { code: 402, txt: '授信余额不足' },
      { code: 404, txt: '授信支付失败' },
      { code: 405, txt: '预存款-授信还款失败！' },
      { code: 408, txt: '授信支付失败！您的授信账户内包含已逾期的账单，请先还款后，再进行支付.' },
    ];
    for (var i = 0, len = list.length; i < len; i++) {
      var item = list[i];
      if (item.code == code)
        return item.txt;
    }
    return res.Message;
  },
  /**
   * 上传凭证
   */
  upload_voucher: (recordToken, src, callback) => {
    var entity = authorize.getEntity();
    var param = {
      recordToken: recordToken || "",
      transferPicture: src,
      Token: entity && entity.manager ? entity.manager.Token : '',
      ProprietorId: app.dns.proprietorId
    };
    util.post("payment.transfer.picture", param,
      function(res) {
        res = res.data;
        if (res.Success) {
          util.alert("上传凭证成功")
          if (callback != undefined && typeof(callback) == "function") {
            callback(res.Content);
          }
        } else {
          util.alert(res.Message);
        }
      }, "3.0",null, false);
  },
}

export {
  cashier,
  orderPay,
  payment
}